package net.gyapp.markim.module.contact;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.easyder.wrapper.base.view.WrapperSwipeActivity;
import com.easyder.wrapper.core.model.BaseVo;
import com.easyder.wrapper.core.scheduler.Task;
import com.easyder.wrapper.core.scheduler.TaskScheduler;
import com.easyder.wrapper.utils.LogUtils;

import net.gyapp.markim.ApiConfig;
import net.gyapp.markim.R;
import net.gyapp.markim.core.ImHelper;
import net.gyapp.markim.core.ImManager;
import net.gyapp.markim.core.ImPrivateUtils;
import net.gyapp.markim.core.entity.ConversationEntity;
import net.gyapp.markim.core.entity.MemberEntity;
import net.gyapp.markim.dao.ConversationEntityDao;
import net.gyapp.markim.dao.DBManager;
import net.gyapp.markim.dao.MemberEntityDao;
import net.gyapp.markim.module.basic.MainActivity;
import net.gyapp.markim.module.basic.base.CommonPresenter;
import net.gyapp.markim.module.basic.event.AccountChanged;
import net.gyapp.markim.module.basic.event.AccountIml;
import net.gyapp.markim.module.mine.account.ModifyTextActivity;
import net.gyapp.markim.utils.RequestParams;

import org.greenrobot.eventbus.EventBus;
import org.jim.common.packets.ChatType;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.winds.widget.usage.TitleView;

/**
 * Author:  winds
 * Data:    2018/10/23
 * Version: 1.0
 * Desc:
 */


public class InfoSetActivity extends WrapperSwipeActivity<CommonPresenter> {

    @BindView(R.id.tv_remark)
    TextView tvRemark;

    MemberEntity entity;

    public static Intent getIntent(Context context, MemberEntity entity) {
        return new Intent(context, InfoSetActivity.class).putExtra("entity", entity);
    }

    @Override
    protected int getViewLayout() {
        return R.layout.activity_info_set;
    }

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        titleView.setCenterText("资料设置");
        getContainerView().setBackgroundColor(ContextCompat.getColor(mActivity, R.color.colorBack));
        entity = (MemberEntity) intent.getSerializableExtra("entity");

        LogUtils.info(entity.toString());

        if (TextUtils.isEmpty(this.entity.remark)) {
            MemberEntity memberEntity = ImHelper.queryMemberEntity(this.entity.memberId);
            if (memberEntity != null) {
                tvRemark.setText(memberEntity.remark != null ? memberEntity.remark : "未设置");
            } else {
                tvRemark.setText("未设置");
            }
        } else {
            tvRemark.setText(this.entity.remark);
        }
    }

    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {

    }

    @Override
    public void showContentView(String url, BaseVo dataVo) {
        if (url.contains(ApiConfig.API_UPDATE_USER_FRIEND)) {
            processDelete();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10001 && resultCode == RESULT_OK) {
            if (data != null) {
                String remark = data.getStringExtra("remark");
                //修改成功
                tvRemark.setText(remark);
                entity.remark = remark;
                setLocalData(entity);
            }
        }
    }

    @OnClick({R.id.layout_set_remark, R.id.btn_delete})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_set_remark:
                if (entity != null) {
                    LogUtils.info("--> " + entity.toString());
                    startActivityForResult(ModifyTextActivity.getIntent
                            (mActivity, TextUtils.isEmpty(entity.remark) ? "设置备注" : "修改备注", entity.remark, "备注字符仅限中英文",
                                    10, ModifyTextActivity.SIGN_MODIFY_REMARK, entity.name), 10001);
                }
                break;
            case R.id.btn_delete:
                if (entity != null) {
                    deleteFriend(entity.memberId);
                }
                break;
        }
    }

    /**
     * 设置本地数据更新
     * @param entity
     */
    private void setLocalData(MemberEntity entity) {
        if (entity != null) {
            MemberEntityDao dao = DBManager.newInstance().getDaoSession().getMemberEntityDao();
            List<MemberEntity> list = dao.queryBuilder().where(MemberEntityDao.Properties.MemberId.eq(entity.memberId),
                    MemberEntityDao.Properties.UserId.eq(ImHelper.getSelfUserId())).list();
            if (list != null && list.size() > 0) {
                for (MemberEntity memberEntity : list) {
                    memberEntity.remark = entity.remark;
                    dao.update(memberEntity);
                }
            }

            ConversationEntityDao conversationEntityDao = DBManager.newInstance().getDaoSession().getConversationEntityDao();
            List<ConversationEntity> conversationEntityList = conversationEntityDao.queryBuilder().where(ConversationEntityDao.Properties.SessionIdStr.eq(entity.memberId),
                    ConversationEntityDao.Properties.ChatType.eq(ChatType.CHAT_TYPE_PRIVATE.getNumber()),
                    ConversationEntityDao.Properties.UserId.eq(ImHelper.getSelfUserId())).list();

            if (conversationEntityList != null && conversationEntityList.size() > 0) {
                conversationEntityList.get(0).name = entity.remark;
                conversationEntityDao.updateInTx(conversationEntityList.get(0));
            }
        }

        EventBus.getDefault().post(new AccountChanged(AccountIml.ACCOUNT_CONTACT_INFO_CHANGED));
    }

    private void deleteFriend(String memberId) {
        presenter.setNeedDialog(true);
        presenter.postData(ApiConfig.API_UPDATE_USER_FRIEND, new RequestParams().put("friendId", memberId)
                .put("status", 0).get(), BaseVo.class);
    }

    private void processDelete() {
        if (entity != null) {
            deleteLocalFriendData(entity.memberId);
        }
    }

    private void deleteLocalFriendData(final String memberId) {
        showLoadingView();
        TaskScheduler.execute(new Task<Boolean>() {
            @Override
            public Boolean doInBackground() throws InterruptedException {
                ImPrivateUtils.clearCache(ImHelper.generateConversation(entity).id);
                ImHelper.deleteFriend(memberId);
                ImManager.getInstance().retryAutoLogin();
                return true;
            }

            @Override
            public void onSuccess(Boolean result) {
                onStopLoading();
                showToast("删除成功");
                EventBus.getDefault().post(new AccountChanged(AccountIml.ACCOUNT_CONTACT_QUIT_GROUP));
                startActivity(MainActivity.getIntent(mActivity));
            }
        });
    }
}
